<?php
$action =   $_GET['action'];
if(!$action){

include_once ("parse/includes.inc");
include_once ("parse/settings.inc");
include_once ("parse/excelparser.php");

if ( !isset($_POST['step']) )
	$_POST['step'] = 0;

?>



<?php

// Outputting fileselect form (step 0)

if ( $_POST['step'] == 0 )
	echo <<<FORM
	
<table width="100%" border="0" align="center" bgcolor="#7EA9D3">
<tr>
<td>&nbsp;</td>
<td>
<p>Select Excel file from your local computer (xls)</p>
</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>

<table border="0">
<form name="exc_upload" method="post" action="" enctype="multipart/form-data">

<tr><td>Excel file:</td><td><input type="file" size=30 name="excel_file"></td></tr>

<tr><td colspan="3" align="left">
<input type="hidden" name="step" value="1">
<input type="button" value="Next" onClick="
javascript:
if( (document.exc_upload.excel_file.value.length==0))
{ alert('You must specify filename first'); return; }; submit();
"></td></tr>


</form>
</table>

</td>
</tr>
</table>

FORM;

       
// Processing excel file (step 1)

if ( $_POST['step'] == 1 ) {

	echo "<br>";

	// Uploading file

	$excel_file = $_FILES['excel_file'];
	if( $excel_file )
		$excel_file = $_FILES['excel_file']['tmp_name'];

	if( $excel_file == '' ) fatal("No file uploaded");

	move_uploaded_file( $excel_file, 'upload/' . $_FILES['excel_file']['name']);
	$excel_file = 'upload/' . $_FILES['excel_file']['name'];


	$fh = @fopen ($excel_file,'rb');
	if( !$fh ) fatal("No file uploaded");
	if( filesize($excel_file)==0 ) fatal("No file uploaded");

	$fc = fread( $fh, filesize($excel_file) );
	@fclose($fh);
	if( strlen($fc) < filesize($excel_file) )
		fatal("Cannot read file");


	// Check excel file

	$exc = new ExcelFileParser ();
	$res = $exc->ParseFromString($fc);

	switch ($res) {
		case 0: break;
		case 1: fatal("Can't open file");
		case 2: fatal("File too small to be an Excel file");
		case 3: fatal("Error reading file header");
		case 4: fatal("Error reading file");
		case 5: fatal("This is not an Excel file or file stored in Excel < 5.0");
		case 6: fatal("File corrupted");
		case 7: fatal("No Excel data found in file");
		case 8: fatal("Unsupported file version");

		default:
			fatal("Unknown error");
	}


	// Pricessing worksheets

	$ws_number = count($exc->worksheet['name']);  
  
	if( $ws_number < 1 ) fatal("No worksheets in Excel file.");

	$ws_number = 0; // Setting to process only the first worksheet
        $ws_n   =   0;
	

        $ws = $exc -> worksheet['data'][$ws_n]; // Get worksheet data
		

        if ( !$exc->worksheet['unicode'][$ws_n] )
                $db_table = $ws_name = $exc -> worksheet['name'][$ws_n];
        else{
            $ws_name = uc2html( $exc -> worksheet['name'][$ws_n] );
            $db_table = convertUnicodeString ( $exc -> worksheet['name'][$ws_n] );
        }

        global $mosConfig_absolute_path, $_photo_path;
        $photo_path =   $_POST['photo_path'];
        $photo_path =   ltrim($photo_path,"/");
        $photo_path =   rtrim($photo_path,"/");
		$_photo_path =	$photo_path;
		
		//thangtd add
		//$photo_path = 	"tmp_photo/".$photo_path."/1.Photos";
		echo $photo_path;
        
        if(!((file_exists($mosConfig_absolute_path."/".$photo_path)) && is_dir($mosConfig_absolute_path."/".$photo_path))){
            echo "<font color='red'>Can not find photo folder : <b>$photo_path</b></font>";
        }
        echo "<div align=\"center\">Worksheet: <b>$ws_name</b></div><br>";
		

        $max_row = $ws['max_row'];
        $max_col = $ws['max_col'];
		$header = array(0=>"ma",1=>"price"); 
		$header_dsp = array(0=>"Ma san pham",1=>"Gia"); 	
	$data_binh = $ws['cell'];
	$sql = array();
	 foreach( $data_binh as $i => $row ) { // Output data and prepare SQL instructions
                    if ( $i == 0 )
                    continue;
                    //echo "<tr bgcolor=\"#ffffff\">";
					$sql[$i]="UPDATE product SET ";
                    for ( $j = 1; $j <= $ws['max_col']; $j++ ) {
                            $_w     =   "";
                            $cell = get ( $exc, $row[$j] );
							$cell0 = get ( $exc, $row[0] );
							//echo $header_dsp[$j]  . ": ". $cell;
							$sql[$i] .= $header[$j] . "='".$cell."' WHERE ".$header[0] . "='".$cell0."' ;   ,'";
							$sql[$i] = substr($sql[$i],0,-2);
							$DB->query($sql[$i]);
                           /* if($j == 13){
                                $_w =   "width='400'";
                            }
							if($j == 1){
                                $_w =   "width='200'";
								if($i <1){
                                echo "<td $_w style='background-color:#EEE;color:#333;'>$cell</td>";
								}else{
									echo "<td $_w>$cell</td>";
								}
								$xx['price']=$cell;
								
                            }else{
								$_w = "width='600'"	;
								if($i <1){
                                echo "<td $_w style='background-color:#EEE;color:#333;'>$cell</td>";
								}else{
									echo "<td $_w>$cell-->";
									$ma=$cell;
									$sql="UPDATE product SET price='".$xx['price']."' WHERE ma='".$ma."'";
									echo $sql;
									$DB->query($sql);	
									echo "</td>";
								}
								
							}
                           */
                    }
					$sql[$i] = substr($sql[$i],0,-2);
					echo "<br>";
                   // echo "</tr>";
                    $i++;
            }   
			//echo "</table>";
			
		echo "<pre>";
			print_r($sql);
		echo "</pre>";	
			$sql = implode("",$sql);
			echo $sql;
			//$DB->query($sql);
			
				
			
			
	/*
	echo "<pre>";
	print_r($ws);
	
	echo "</pre>"; */
        //if ( $max_row > 0 && $max_col > 0 )
               // getTableData ( &$ws, &$exc ); // Get structure and data of worksheet
        //else fatal("Empty worksheet");
		//echo "<input type='text' name='photo_path' value='".$photo_path."' />";
        
}
}
function processProductImageUrl($origin_url,$origin_userid)
{
        
        $new_url    =   str_replace('/'.$origin_userid.'/', '/9/', $origin_url);
        $pieces     =   explode('/', $new_url);
        $image_name =   $pieces[count($pieces)-1];
        unset($pieces[count($pieces)-1]);
        array_push($pieces, $origin_userid);
        array_push($pieces, $image_name);        
        $new_url    =   implode('/', $pieces);
        return $new_url;
}

function insertProduct($product = array())
{    
    global $database;
    $fields  =   array();
    $values  =   array();
    foreach($product as $k=>$v){
        array_push($fields, $k);
        array_push($values, "'".$v."'");
    }

    $query  =   "INSERT INTO cani_product(".implode(",", $fields).") VALUES (".implode(",", $values).")";
    $database->setQuery($query);    
    $database->query();

    $sql_last_insert    =   'SELECT LAST_INSERT_ID() FROM cani_product';
    $cur                =   mysql_query($sql_last_insert);
    $row    =   mysql_fetch_array($cur);
    $last_insert_id = $row[0];
    mysql_free_result($sql_last_insert);
    return $last_insert_id;
}

/*functions which  used form importin*/
function getCatNameById($cat_id,$user_id = 0)
{
    global $database;
    $query  =   "select category_name from cani_category WHERE category_id=".$cat_id."";
    if($user_id){
        $query.='AND user_id='.$user_id;
    }    
    $database->setQuery($query);
    return $database->loadResult();
}

function getGroupByName($cat_name)
{
    global $database;
    $query  =   "select category_id from cani_category WHERE user_id=9 and category_name='".$cat_name."'";
    $database->setQuery($query);    
    return $database->loadResult();
}

function insertCategory2($cat = array())
{
	global $database;
	$fields  =   array();
	$values  =   array();
	foreach($cat as $k=>$v){
		array_push($fields, $k);
		array_push($values, "'".$v."'");
	}

	$query  =   "INSERT INTO cani_category(".implode(",", $fields).") VALUES (".implode(",", $values).")";        
	$database->setQuery($query);
	if($database->query()){
		$query  =   "SELECT LAST_INSERT_ID() FROM cani_category";
		$database->setQuery($query);
		return $database->loadResult();
	}else{
		return false;
	}
	
}

function setExcelFilename()
{
	
}
?>